package devicedbgui;

import devicedbgui.data.Device;
import devicedbgui.data.MAC;
import devicedbgui.data.MACDAO;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import macdbgui.EditMACDlg;

/** Stores MAC addresses*/
public class MACPanel extends javax.swing.JPanel {
    
    /** Reference to GUI class for accessing its variables */
     public GUI gui;
    Hashtable<Integer, MAC> htMAC = new Hashtable<Integer, MAC>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    /** Constructor creates all components belonging to panel */ 
    public MACPanel() {
        initComponents();
    }
     /** Displays error messages */ 
 public void showError(JFrame parent, String error)
    {
        JOptionPane.showMessageDialog(parent, error);
    }
    /** Displays MAC addresses associated with device */
    public void showMACs(GUI gui, Device device)
    {
        this.gui = gui;
//        this.setTitle("MACs");
        MACDAO dd = new MACDAO(gui.connection);
        try {
            ArrayList<MAC> records = dd.selectByDevice(device.record);
            DefaultTableModel model = (DefaultTableModel)tblMAC.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htMAC.clear();
            for (MAC item : records){ 
                htMAC.put(new Integer(index++), item);
                model.addRow(new Object[]{item.purchasedMAC, sdf.format(item.timeAssigned), item.Device_record});
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
     }
    /** Displays all MAC addresses available in database  */
    public void showAll(GUI gui)
    {
        this.gui = gui;
        MACDAO dd = new MACDAO(gui.connection);
        try {
            ArrayList<MAC> records = dd.selectAll();
            DefaultTableModel model = (DefaultTableModel)tblMAC.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htMAC.clear();
            for (MAC item : records){ 
                htMAC.put(new Integer(index++), item);
                model.addRow(new Object[]{item.purchasedMAC, sdf.format(item.timeAssigned), item.Device_record});
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
     }
     /** Refreshes display of list of builds in database */
    public void update()
    {
        MACDAO dd = new MACDAO(gui.connection);
        try {
            ArrayList<MAC> records = dd.selectAll();
            DefaultTableModel model = (DefaultTableModel)tblMAC.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htMAC.clear();
            for (MAC item : records){ 
                htMAC.put(new Integer(index++), item);
                model.addRow(new Object[]{item.purchasedMAC, sdf.format(item.timeAssigned), item.Device_record});
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblMAC = new javax.swing.JTable(){    public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !tblMAC.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (tblMAC.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }
    }
    ;
    btnEdit = new javax.swing.JButton();
    btnDelete = new javax.swing.JButton();
    btnAdd = new javax.swing.JButton();

    tblMAC.setAutoCreateRowSorter(true);
    tblMAC.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null}
        },
        new String [] {
            "Purchased MAC", "Time assigned", "Device Record"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    tblMAC.setGridColor(new java.awt.Color(204, 204, 255));
    tblMAC.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jScrollPane1.setViewportView(tblMAC);

    btnEdit.setText("Edit");
    btnEdit.setMnemonic(KeyEvent.VK_I);
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    btnDelete.setText("Delete");
    btnDelete.setMnemonic(KeyEvent.VK_DELETE);
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    btnAdd.setText("Add");
    btnAdd.setMnemonic(KeyEvent.VK_D);
    btnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnAddActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnEdit)
                .addComponent(btnDelete))
            .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit});

    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(btnAdd)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnEdit)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnDelete)))
            .addContainerGap())
    );
    }// </editor-fold>//GEN-END:initComponents
/** Edit MAC information */
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
int[] selected = tblMAC.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    MAC item = htMAC.get(new Integer(selected[0]));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    EditMACDlg dlg = new EditMACDlg(gui, item, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        htMAC.remove(new Integer(selected[0]));        
        htMAC.put(new Integer(selected[0]), dlg.mac);
        update();
    }
}//GEN-LAST:event_btnEditActionPerformed
/* Delete selected MAC */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int[] selected = tblMAC.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    // ask user if he surely wants to delete this record
    int option = JOptionPane.showConfirmDialog(gui.frame, "Are you sure to delete selected record(s)?", "Confirmation", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION)
    {        
        MACDAO dd = new MACDAO(gui.connection);
        try {
            for (int i = 0; i < selected.length; i++){
                MAC item = htMAC.get(new Integer(selected[i]));   
                dd.delete(item.purchasedMAC);
                htMAC.remove(new Integer(selected[i]));

            }           
            
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
        update();
    }
}//GEN-LAST:event_btnDeleteActionPerformed
/* Add MAC information to database */
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
//if (gui.connection == null)
        //return;
    EditMACDlg dlg = new EditMACDlg(gui, null, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        update();
    }
}//GEN-LAST:event_btnAddActionPerformed
 

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblMAC;
    // End of variables declaration//GEN-END:variables

}
